<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/6/7
 * Time: 11:22
 */

namespace common\controllers;


use Yii;
use yii\base\Exception;
use yii\base\UserException;
use yii\web\HttpException;


class ErrorAction extends \yii\web\ErrorAction
{
    public function run()
    {
        if (($exception = Yii::$app->getErrorHandler()->exception) === null) {
            // action has been invoked not from error handler, but by direct route, so we display '404 Not Found'
            $exception = new HttpException(404, Yii::t('yii', 'Page not found.'));
        }

        if ($exception instanceof HttpException) {
            $code = $exception->statusCode;
        } else {
            $code = $exception->getCode();
        }
        if ($exception instanceof Exception) {
            $name = $exception->getName();
        } else {
            $name = $this->defaultName ?: Yii::t('yii', 'Error');
        }


        if ($exception instanceof UserException) {
            $message = $exception->getMessage();
        } else {
            $message = $this->defaultMessage ?: Yii::t('yii', 'An internal server error occurred.');
        }

        if (Yii::$app->getRequest()->getIsAjax()) {
            echo json_encode(
                [
                    'name'=>$name,
                    'msg' =>$message
                ]
            );
        } else {
            echo json_encode(
                [
                    'status'=>'error',
                    'code'=>$code,
                    'msg' =>$message,
                ]
            );
        }
    }

}